package HttpThread;


import Dispatch.DispatcherService;
import HttpBean.Request.Request;
import HttpBean.Request.RequestImpl.RequestGetReadBufferImpl;
import HttpBean.Request.RequestImpl.RequestPostReadBufferImpl;
import HttpBean.Request.RequestLine;
import HttpBean.Response.Response;

import java.io.*;
import java.net.Socket;

public class HttpThread implements Runnable {
    Socket socket;

    public HttpThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Request request;
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
            RequestLine requestLine;
            try {
                requestLine = new RequestLine(reader.readLine());
            }catch (NullPointerException e){
                System.out.println("连接异常");
                return;
            }
            if(requestLine.getMethod().equals("GET")) {
                request = new RequestGetReadBufferImpl(reader, requestLine);
            }else{
                request = new RequestPostReadBufferImpl(reader, requestLine);
            }
            System.out.println(request.toString());
            Response response = DispatcherService.doDispatch(request);
            outputStream.write(response.getResponse().getBytes());
            outputStream.flush();
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
